<template>
  <basic-dialog
    :visible="show"
    :title="`${isEdit ? '编辑' : '添加'}领用申请`"
    :isShowInnerLoading="isShowInnerLoading"
    min-width="1000px"
  >
    <q-form
      @submit="onSubmit"
      autocapitalize
      greedy
      @reset="onReset"
      ref="myForm"
      class="dialog-content form-inline block no-padding"
    >
      <div class="row margin-t-20">
        <div class="col-4 flex">
          <yz-input
            v-model="queryParams.date"
            inputType="date"
            :isRange="false"
            :rules="[0]"
            class="datepicker"
            title="期望日期"
          />
        </div>
        <div class="col-4">
          <yz-input
            v-model="queryParams.departmentId"
            inputType="select"
            :rules="[0]"
            ref="department"
            @on-select="changeDepartment"
            :options="departmentsList"
            title="领用部门"
          />
        </div>
        <div class="col-4">
          <yz-input
            v-model="queryParams.userId"
            inputType="select"
            :rules="[0]"
            :options="peopleList"
            ref="userId"
            title="领用人员"
          />
        </div>
        <div class="col-4">
          <yz-input
            v-model="queryParams.category"
            inputType="select"
            :rules="[0]"
            @input="selectCate"
            :options="$getEnum(Enums.APPLY_OPTIONS)"
            ref="category"
            title="领用类型"
          />
        </div>
        <div class="col-4 font-size-16 margin-l-10">
          关联单号：{{ queryParams.orderNumber || "" }}
          <q-tooltip>{{ queryParams.orderNumber || "" }}</q-tooltip>
        </div>
        <q-btn
          class="btn q-ml-lg"
          outline
          :disabled="queryParams.orderType == ''"
          color="primary"
          label="选择"
          @click="onSelectOrder"
        />
      </div>
      <q-separator />
      <div class="page-content padding-b-20 padding-t-20">
        <div
          class="spare-table-header flex items-center justify-center relative-position"
        >
          <div class="font-14 text-weight-bold flex">
            <div style="width: 60px">领用列表</div>
          </div>
          <q-icon
            name="iconfont icontubiao-39"
            @click.native="isShowSelToolDialog = true"
            class="float-right q-mr-md cursor-pointer absolute-right"
            style="margin-top:15px; color:#5F77FD; font-size: 20px"
          >
            <q-tooltip>添加</q-tooltip>
          </q-icon>
        </div>
        <q-table
          :data="tableData"
          :columns="tableColumns"
          row-key="id"
          class="myTable scroll stick-last-col inherit"
          style="margin: 0 20px;max-height: 280px"
          :pagination.sync="pagination"
          :hide-bottom="!!tableData.length"
          no-data-label="暂无数据"
          loading-label="加载中..."
          :loading="isTableLoading"
          color="primary"
        >
          <template v-slot:body-cell-cutterNumber="props">
            <q-td>
              <span
                :id="`scrollFlag_${props.row.__index}`"
                class="absolute-top-left"
                style="top:-50px"
              />
              {{ props.row.cutterNumber }}
            </q-td>
          </template>
          <template v-slot:body-cell-count="props">
            <q-td class="" style="padding: 14px 5px 0 0">
              <yz-input
                v-model="props.row.count"
                style="width: 120px"
                :rules="[0, 3, 4]"
                :maxlength="4"
              />
              <!--              :hintRule="setInspectQuantityRules(props.row)"-->
            </q-td>
          </template>
          <template v-slot:body-cell-operate="props">
            <q-td class="operate" style="width: 60px">
              <div class="btn-group text-center">
                <table-btn btnType="delete" @click="onDeleteRow(props.row)" />
              </div>
            </q-td>
          </template>
        </q-table>
      </div>
      <yz-input
        class="margin-l-20 margin-r-20 name-auto"
        v-model.trim="queryParams.remark"
        inputType="textarea"
        :maxlength="100"
        title="备注"
      />
      <q-separator />
      <div class="dialog-footer text-center" style="padding: 10px 0">
        <q-btn
          outline
          label="取消"
          color="primary"
          class="q-mr-md"
          type="reset"
        />
        <q-btn
          unelevated
          label="确认"
          v-throttle
          color="primary"
          :disable="!tableData.length || !queryParams.orderNumber"
          type="submit"
        />
      </div>
    </q-form>
    <select-spare-dialog
      :open="isShowSelToolDialog"
      @close="isShowSelToolDialog = false"
      @onSetCutter="onSetCutter"
      :cutterData="tableData"
      :isMultiple="true"
    />
    <associated-order-dialog
      ref="associatedOrderDialog"
      :orderType="queryParams.orderType"
      :selData="tableData"
      @successAll="successAll"
    />
  </basic-dialog>
</template>

<script>
import * as lendReturn from 'src/boot/inventory/lend-return'
import _ from 'lodash'
import moment from 'moment'
import SelectSpareDialog from '../../inventory/components/select-spare-dialog'
import AssociatedOrderDialog from './associated-order-dialog'
import { getOneApply, saveApply, updateApply } from '../../../boot/spare/parts'
// import moment from 'moment'
export default {
  name: 'add-edit-dialog',
  components: {
    AssociatedOrderDialog,
    SelectSpareDialog
  },
  props: {},
  data () {
    return {
      editData: {},
      show: false,
      isEdit: false,
      productList: [],
      processList: [],
      queryParams: {
        remark: '',
        date: new Date(),
        orderType: '',
        orderId: '',
        category: '',
        orderNumber: '',
        departmentId: '',
        userId: '',
        spareParts: []
      },
      tableColumns: [
        { name: 'number', label: '备件编号', align: 'left', field: 'number' },
        { name: 'name', label: '备件名称', align: 'left', field: 'name' },
        {
          name: 'categoryName',
          label: '所属分类',
          align: 'left',
          field: 'categoryName'
        },
        { name: 'spec', label: '规格', align: 'left', field: 'spec' },
        { name: 'unitName', label: '单位', align: 'left', field: 'unitName' },
        {
          name: 'sparePartCount',
          label: '库存数量',
          field: 'sparePartCount',
          align: 'left'
        },
        {
          name: 'count',
          label: '领用数量',
          field: 'count',
          align: 'left'
        },
        { name: 'operate', label: '操作', field: 'operate', align: 'left' }
      ],
      tableData: [],
      departmentsList: [], // 部门数据源
      peopleList: [], // 人员列表
      // 表格分页配置
      pagination: {
        // 总条数
        rowsNumber: 0
      },
      isTableLoading: false,
      isShowSelToolDialog: false,
      isShowInnerLoading: false
    }
  },
  watch: {
    'queryParams.category': {
      handler (val) {
        switch (val) {
          case '维修领用':
            this.queryParams.orderType = 1
            break
          case '保养领用':
            this.queryParams.orderType = 2
            break
          case '其他':
          case '':
            this.queryParams.orderType = ''
            break
        }
      }
    }
  },
  methods: {
    selectCate () {
      this.queryParams.orderNumber = ''
    },
    onSelectOrder () {
      this.$refs.associatedOrderDialog.showDialog()
    },
    successAll (val, number, orderId) {
      this.queryParams.orderNumber = number
      this.queryParams.orderId = orderId
      const flag = this.tableData.length
      this.tableData = _.uniqBy([...this.tableData, ...val], 'id')
      this.$nextTick(() => {
        document.getElementById(`scrollFlag_${flag}`).scrollIntoView()
      })
    },
    showDialog (type, editData) {
      this.show = true
      this.editData = editData
      this.isEdit = type === 'edit'
      this.isShowInnerLoading = true
      this.processList = []
      this.peopleList = []
      if (this.isEdit) {
        this.getDepartments()
        this.getClaimOrdersById() // 编辑时候的详情
      } else {
        this.getDepartments()
      }
    },
    // 非昨日之前
    notBeforeToday (date) {
      const today = moment(new Date()).startOf('day')
      return date < new Date(today)
    },
    // 检验数量校验
    setInspectQuantityRules (row) {
      const { stockQuantity } = row
      let member = Number(stockQuantity)
      return [val => Number(val) <= member || `不能超过库存总数`]
    },
    // 切换部门
    changeDepartment (id, userId = null, isFirst = true) {
      this.isShowInnerLoading = true
      lendReturn
        .getPeople(id)
        .then(res => {
          const peopleList = []
          res.forEach(item => {
            peopleList.push({
              label: item.name,
              value: item.id
            })
          })
          this.peopleList = peopleList
          this.queryParams.userId = _.isNil(userId)
            ? isFirst
              ? _.get(peopleList[0], 'value', null)
              : null
            : userId
          this.isShowInnerLoading = false
        })
        .finally(() => {
          this.isShowInnerLoading = false
          this.$refs.userId.validateVal()
          this.$refs.department.validateVal()
        })
      // 获取部门下人员
    },
    // 选择刀具
    async onSetCutter (data) {
      this.isShowInnerLoading = true
      // const id = this.isEdit ? this.queryParams.id : undefined
      const flag = this.tableData.length
      this.tableData = _.uniqBy([...this.tableData, ...data], 'id')
      this.isShowSelToolDialog = false
      this.isShowInnerLoading = false
      this.$nextTick(() => {
        document.getElementById(`scrollFlag_${flag}`).scrollIntoView()
      })
    },
    // save add
    submitProcessOrders () {
      const params = {
        ...this.queryParams
      }
      params.spareParts = this.tableData.map(v => {
        return {
          count: v.count,
          sparePartId: v.id
        }
      })
      console.log(params)
      params.date = moment(this.queryParams.date).format('YYYY-MM-DD')
      !this.isEdit && this.createApplyUse(params)
      this.isEdit && this.editApplyUse({ ...params, id: this.editData.id })
    },
    // 创建领用申请
    createApplyUse (params) {
      saveApply(params)
        .then(res => {
          this.isShowInnerLoading = false
          this.$message.success('操作成功')
          this.onReset(true)
        })
        .finally(() => {
          this.isShowInnerLoading = false
        })
    },
    // 编辑领用申请
    editApplyUse (params) {
      updateApply(params)
        .then(res => {
          this.isShowInnerLoading = false
          this.$message.success('操作成功')
          this.onReset(true)
        })
        .finally(() => {
          this.isShowInnerLoading = false
        })
    },
    // 删除行
    onDeleteRow (row) {
      const member = _.cloneDeep(this.tableData)
      this.tableData = member.filter(v => v['__index'] !== row['__index']) // 根据index删除
    },
    // 重置
    onReset (val = false) {
      Object.assign(
        this.queryParams,
        this.$options.data.call(this).queryParams
      )
      this.tableData = []
      this.departmentsList = []
      this.peopleList = []
      this.$emit('getList')
      this.show = false
    },
    onSubmit () {
      this.isShowInnerLoading = true
      if (this.notBeforeToday(this.queryParams.date)) {
        this.$message.warning('申请日期不可早于当日')
        this.isShowInnerLoading = false
      } else {
        this.submitProcessOrders()
      }
    },
    /**
     * 获取部门
     */
    getDepartments () {
      this.isShowInnerLoading = true
      lendReturn
        .getDepartments()
        .then(data => {
          data.forEach(item => {
            item.value = item.id
          })
          this.departmentsList = data
          this.isShowInnerLoading = false
        })
        .catch(err => {
          this.isShowInnerLoading = false
          console.log(err)
        })
    },
    // edit detail
    getClaimOrdersById () {
      const { id } = this.editData
      this.tableData = []
      getOneApply(id)
        .then(ret => {
          this.isShowInnerLoading = false
          Object.keys(this.queryParams).map(v => {
            this.$set(this.queryParams, v, ret.data[v] || '')
          })
          this.$nextTick(() => {
            this.queryParams.orderNumber = ret.data.orderNumber
          })
          this.queryParams.date = new Date(ret.data.date)
          this.changeDepartment(ret.data.departmentId, ret.data.userId)
          this.tableData = ret.data.applyDetails.map(v => {
            return {
              ...v,
              id: v.sparePartId,
              name: v.sparePartName,
              number: v.sparePartNumber,
              categoryName: v.sparePartCategory,
              spec: v.sparePartSpec,
              unitName: v.sparePartUnit
            }
          })
        })
        .catch(err => {
          console.log(err)
          this.isShowInnerLoading = false
        })
    }
  }
}
</script>

<style scoped lang="stylus">
.spare-table-header {
  width: calc(100% - 40px);
  margin auto;
  height: 48px;
  line-height: 48px;
  background: #f3f3f3;
  //border: 1px solid #d3d3d3;
  border-bottom: 0px;
  border-radius: 3px 3px 0px 0px;
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #333333;
}
  .cursor-pointer{
    >>>.q-field__inner{
      cursor: pointer
    }
    >>>.q-field__control-container{
      opacity 1 !important
    }
  }
  .col-4{
    padding 0 10px
  }
  >>>.mx-datepicker{
    width 210px !important
  }
  .name-auto{
    >>>.name{
      width auto
    }
  }
</style>
